import Foundation
import Combine

// AI服务协议
protocol AIServiceProtocol {
    var isProcessing: Bool { get }
    var processingPublisher: Published<Bool>.Publisher { get }
    
    func processNaturalLanguageCommand(_ command: String, completion: @escaping (AICommandResult) -> Void)
    func cancelProcessing()
}

// AI命令结果
struct AICommandResult {
    let success: Bool
    let commands: [CarControlCommand]
    let message: String
    let error: String?
    
    init(success: Bool, commands: [CarControlCommand] = [], message: String = "", error: String? = nil) {
        self.success = success
        self.commands = commands
        self.message = message
        self.error = error
    }
}

// AI服务实现
class AIService: ObservableObject, AIServiceProtocol {
    // MARK: - 属性
    @Published var isProcessing: Bool = false
    var processingPublisher: Published<Bool>.Publisher { $isProcessing }
    
    // API配置
    private let baseURL = "https://ark.cn-beijing.volces.com/api/v3"
    private let apiKey = "6df25e7d-fd48-4025-bff6-4f21ce65e9e1"
    private let model = "doubao-seed-1-6-250615"
    
    // 网络会话
    private let session = URLSession.shared
    
    // 取消器
    private var cancellables = Set<AnyCancellable>()
    
    // 当前请求任务
    private var currentTask: URLSessionDataTask?
    
    // MARK: - 公共方法
    func processNaturalLanguageCommand(_ command: String, completion: @escaping (AICommandResult) -> Void) {
        guard !command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            completion(AICommandResult(success: false, error: "命令不能为空"))
            return
        }
        
        // 取消当前正在进行的请求
        cancelProcessing()
        
        isProcessing = true
        
        // 构建请求
        let request = buildAIRequest(command: command)
        
        // 发送请求
        currentTask = session.dataTask(with: request) { [weak self] data, response, error in
            DispatchQueue.main.async {
                // 检查是否已被取消
                guard self?.isProcessing == true else {
                    return
                }
                
                self?.isProcessing = false
                self?.currentTask = nil
                
                if let error = error {
                    // 检查是否是取消错误
                    if (error as NSError).code == NSURLErrorCancelled {
                        completion(AICommandResult(success: false, error: "请求已取消"))
                    } else {
                        completion(AICommandResult(success: false, error: "网络错误: \(error.localizedDescription)"))
                    }
                    return
                }
                
                guard let data = data else {
                    completion(AICommandResult(success: false, error: "未收到响应数据"))
                    return
                }
                
                // 解析响应
                self?.parseAIResponse(data: data, completion: completion)
            }
        }
        
        currentTask?.resume()
    }
    
    func cancelProcessing() {
        // 取消当前请求
        currentTask?.cancel()
        currentTask = nil
        isProcessing = false
    }
    
    // MARK: - 私有方法
    private func buildAIRequest(command: String) -> URLRequest {
        let url = URL(string: "\(baseURL)/chat/completions")!
        var request = URLRequest(url: url)
        
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        
        // 构建请求体
        let requestBody: [String: Any] = [
            "model": model,
            "messages": [
                [
                    "role": "system",
                    "content": buildSystemPrompt()
                ],
                [
                    "role": "user",
                    "content": command
                ]
            ],
            "max_tokens": 10000,  // 增加最大token数量以支持更长的动作序列
            "temperature": 0.1
        ]
        
        request.httpBody = try? JSONSerialization.data(withJSONObject: requestBody)
        return request
    }
    
    private func buildSystemPrompt() -> String {
        return """
        你是一个智能小车控制助手。用户会用自然语言描述小车的移动需求，你需要将其转换为具体的控制命令。

        小车支持两种控制模式，速度分量范围均为-100到+100：

        1. 速度控制原理：
           - X轴分量 (num_x): 控制小车的左右运动 (-100到+100)
           - Y轴分量 (num_y): 控制小车的前进和后退 (-100到+100)
           - 速度范围: -100到+100，对应0%到100%的功率

        2. 运动类型区分（重要）：
           - **前进/后退**：num_x=0, num_y≠0 (如前进: num_y=50, 后退: num_y=-50)
           - **原地旋转**：num_x≠0, num_y=0 (如左旋转: num_x=-50, 右旋转: num_x=50)
           - **平移**：num_x≠0, num_y=0 (与旋转速度分量相同，但在description中区分)

        3. 关键区分（走图形的核心）：
           - **"转弯"、"左转"、"右转"、"旋转"**：都是原地旋转，description必须包含"旋转"字样
           - **"平移"、"左平移"、"右平移"**：侧向移动，description必须包含"平移"字样  
           - **走正方形时的转角**：必须使用"旋转"，不能用"平移"！

        4. 速度级别：
           - 低速: 20-40% (num_x/num_y: ±20到±40)
           - 中速: 50-70% (num_x/num_y: ±50到±70)
           - 高速: 80-100% (num_x/num_y: ±80到±100)

        5. 动作时间范围（支持精细控制）：
           - 最短动作：0.1秒（适合快速舞蹈动作）
           - 短动作：0.2-0.5秒（适合节拍舞蹈）
           - 基础动作：0.5-1.0秒（基本移动）
           - 长动作：1.0-5.0秒（长距离移动）
           - 超长动作：5.0-10.0秒（特殊需求）

        6. 旋转度数与时间映射（重要）：
           - 低速旋转：81度/秒 (15度≈0.19秒, 30度≈0.37秒, 45度≈0.56秒, 90度≈1.11秒, 180度≈2.22秒, 360度≈4.44秒)
           - 中速旋转：135度/秒 (15度≈0.11秒, 30度≈0.22秒, 45度≈0.33秒, 90度≈0.67秒, 180度≈1.33秒, 360度≈2.67秒)
           - 高速旋转：216度/秒 (15度≈0.07秒, 30度≈0.14秒, 45度≈0.21秒, 90度≈0.42秒, 180度≈0.83秒, 360度≈1.67秒)

        7. 舞蹈动作支持：
           - **快速舞蹈**: 每个动作0.1-0.3秒，连续性强
           - **节拍舞蹈**: 每个动作0.2-0.5秒，配合音乐节拍
           - **舞步组合**: 可以输出50+个连续动作
           - **动作变化**: 支持速度、方向、旋转的快速切换
           - **暂停动作**: 可以在动作之间插入停止命令（speed_x=0, speed_y=0）

        8. 复杂动作序列支持：
           - 最大命令数量：100个（支持长时间复杂表演）
           - 组合动作：可以结合前进、后退、旋转、平移创造复杂轨迹
           - 变速动作：同一动作可以使用不同速度创造节奏感
           - 重复模式：可以重复特定动作序列

        9. 鸣笛音响控制（新增！重要）：
           - **鸣笛指令**: 用于在舞蹈和动作中播放节奏型音乐
           - **鸣笛类型**: 
             * "short": 短促鸣笛（0.1秒，适合快节拍）
             * "medium": 中等鸣笛（0.2秒，适合标准节拍）
             * "long": 长鸣笛（0.3秒，适合重音节拍）
             * "beat": 节拍鸣笛（0.1秒，专用于舞蹈节拍）
             * "rhythm": 节奏鸣笛（0.2秒，专用于音乐伴奏）
           - **鸣笛配合**: 与移动动作同步使用，创造音响效果
           - **节奏模式**: 在舞蹈中每2-4个动作配一次鸣笛，形成音乐节拍
           - **音乐创作**: 可以仅使用鸣笛创作简单的音乐旋律

        请按照以下JSON格式返回控制命令序列：
        {
            "commands": [
                {
                    "speed_x": 0,
                    "speed_y": 50,
                    "duration": 0.5,
                    "description": "前进50%速度0.5秒"
                },
                {
                    "horn_type": "beat",
                    "duration": 0.1,
                    "description": "节拍鸣笛0.1秒"
                }
            ],
            "description": "执行说明"
        }

        舞蹈示例（带鸣笛音乐）：
        - "跳一段简单的舞" -> [前进0.3秒, 节拍鸣笛0.1秒, 左旋转45度0.21秒, 后退0.3秒, 节拍鸣笛0.1秒, 右旋转45度0.21秒, 停止0.2秒, 重复...]
        - "快速摆动舞" -> [左平移0.2秒, 短促鸣笛0.1秒, 右平移0.2秒, 短促鸣笛0.1秒, 左平移0.2秒, 短促鸣笛0.1秒...]
        - "旋转舞" -> [高速左旋转0.1秒, 节拍鸣笛0.1秒, 停止0.1秒, 高速右旋转0.1秒, 节拍鸣笛0.1秒, 停止0.1秒...]
        - "8字舞" -> [前进+左旋转组合, 节奏鸣笛, 前进+右旋转组合, 节奏鸣笛, 形成8字路径配音乐]
        - "播放节拍音乐" -> [仅使用不同类型的鸣笛创造音乐: 短促-中等-长-短促-短促-中等...]

        基础示例：
        - "走正方形" -> [前进1秒, 右旋转90度0.67秒, 前进1秒, 右旋转90度0.67秒, 前进1秒, 右旋转90度0.67秒, 前进1秒, 右旋转90度0.67秒]
        - "前进10米" -> [前进60%5秒]
        - "左转90度" -> [num_x=-50, num_y=0, duration=0.67, description="左旋转90度"]
        - "右转180度" -> [num_x=50, num_y=0, duration=1.33, description="右旋转180度"]
        - "播放简单音乐" -> [短促鸣笛0.1秒, 停止0.1秒, 中等鸣笛0.2秒, 停止0.2秒, 长鸣笛0.3秒, 停止0.1秒, 重复...]

        鸣笛指令格式（支持高自由度音乐创作）：
        - 鸣笛命令使用 "horn_type" 字段，不需要 speed_x 和 speed_y
        - "duration" 字段直接指定鸣笛持续时间（0.05-2.0秒），支持精确到0.01秒
        - 预定义鸣笛类型（会结合duration调整）:
          * "short"/"短": 短促鸣笛（≤0.1秒）
          * "medium"/"中": 中等鸣笛（~0.15秒）
          * "long"/"长": 长鸣笛（≥0.3秒）
          * "beat"/"节拍": 节拍鸣笛（使用指定duration）
          * "rhythm"/"旋律": 旋律鸣笛（使用指定duration）
          * "tick"/"滴答": 极短滴答声（≤0.06秒）
          * "quarter"/"四分": 四分音符（≥0.25秒）
          * "half"/"二分": 二分音符（≥0.5秒）
          * "whole"/"全音": 全音符（≥1.0秒）
          * "sustained"/"持续": 持续音（≥1.5秒）
        - 数值鸣笛: horn_type可以直接写数字，如"0.15"表示0.15秒鸣笛
        - 自由组合: 可以用任意duration创造复杂音乐节拍
        
        鸣笛音乐示例：
        - 简单节拍: [{"horn_type": "0.1", "duration": 0.1}, {"horn_type": "0.2", "duration": 0.2}]
        - 复杂旋律: [{"horn_type": "tick", "duration": 0.05}, {"horn_type": "0.15", "duration": 0.15}, {"horn_type": "quarter", "duration": 0.3}]
        - 与动作配合: [动作命令, {"horn_type": "beat", "duration": 0.12}, 动作命令, {"horn_type": "0.08", "duration": 0.08}]

        注意：
        - speed_x和speed_y的范围都是-100到+100
        - 支持0.1秒的精细时间控制
        - 舞蹈类命令请生成20-50个动作序列，其中20-30%应包含鸣笛指令
        - 可以使用停止命令(0,0)创造节拍感
        - 旋转命令必须使用准确的度数-时间映射
        - 鸣笛指令应与动作协调，形成音乐节拍感
        - 请确保命令合理且安全，避免过高的速度值
        - 对于复杂动作，请详细描述每个步骤
        - 在舞蹈中合理使用鸣笛创造音响效果
        """
    }
    
    private func parseAIResponse(data: Data, completion: @escaping (AICommandResult) -> Void) {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
            
            guard let choices = json?["choices"] as? [[String: Any]],
                  let firstChoice = choices.first,
                  let message = firstChoice["message"] as? [String: Any],
                  let content = message["content"] as? String else {
                completion(AICommandResult(success: false, error: "响应格式错误"))
                return
            }
            
            // 解析AI返回的JSON命令
            let commands = parseCommandsFromAIResponse(content)
            
            if commands.isEmpty {
                print("[AIService] 命令解析失败，AI响应内容: \(content)")
                completion(AICommandResult(success: false, error: "无法解析控制命令，AI响应格式可能有误"))
            } else {
                print("[AIService] 成功解析 \(commands.count) 个命令")
                completion(AICommandResult(success: true, commands: commands, message: "成功解析 \(commands.count) 个控制命令"))
            }
            
        } catch {
            completion(AICommandResult(success: false, error: "解析响应失败: \(error.localizedDescription)"))
        }
    }
    
    private func parseCommandsFromAIResponse(_ response: String) -> [CarControlCommand] {
        print("[AIService] 开始解析AI响应: \(response)")
        
        // 方法1: 尝试寻找完整的JSON对象
        if let jsonString = extractJSONFromResponse(response) {
            if let commands = parseJSONCommands(jsonString) {
                return commands
            }
        }
        
        // 方法2: 尝试解析整个响应作为JSON
        if let commands = parseJSONCommands(response) {
            return commands
        }
        
        print("[AIService] JSON解析失败，尝试文本解析")
        return []
    }
    
    private func extractJSONFromResponse(_ response: String) -> String? {
        // 寻找第一个 { 和最后一个 }
        guard let jsonStart = response.range(of: "{") else {
            print("[AIService] 未找到JSON开始标记")
            return nil
        }
        
        guard let jsonEnd = response.range(of: "}", options: .backwards) else {
            print("[AIService] 未找到JSON结束标记")
            return nil
        }
        
        // 安全检查索引边界
        guard jsonStart.lowerBound < jsonEnd.upperBound else {
            print("[AIService] JSON范围无效")
            return nil
        }
        
        // 使用更安全的字符串截取方法
        let startIndex = jsonStart.lowerBound
        let endIndex = jsonEnd.upperBound
        
        guard startIndex < response.endIndex && endIndex <= response.endIndex else {
            print("[AIService] 字符串索引越界")
            return nil
        }
        
        let jsonString = String(response[startIndex..<endIndex])
        print("[AIService] 提取的JSON字符串: \(jsonString)")
        return jsonString
    }
    
    private func parseJSONCommands(_ jsonString: String) -> [CarControlCommand]? {
        guard let data = jsonString.data(using: .utf8) else {
            print("[AIService] 字符串转换为Data失败")
            return nil
        }
        
        do {
            let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
            
            guard let commandsArray = json?["commands"] as? [[String: Any]] else {
                print("[AIService] 未找到commands数组")
                return nil
            }
            
            var carCommands: [CarControlCommand] = []
            
            for (index, commandDict) in commandsArray.enumerated() {
                if let command = parseSingleCommand(commandDict) {
                    carCommands.append(command)
                    print("[AIService] 成功解析命令 \(index + 1): \(command.direction.rawValue)")
                } else {
                    print("[AIService] 解析命令 \(index + 1) 失败: \(commandDict)")
                }
            }
            
            print("[AIService] 总共解析出 \(carCommands.count) 个命令")
            return carCommands
            
        } catch {
            print("[AIService] JSON序列化失败: \(error)")
            return nil
        }
    }
    
    private func parseSingleCommand(_ commandDict: [String: Any]) -> CarControlCommand? {
        print("[AIService] 解析单个命令: \(commandDict)")
        
        // 鸣笛指令格式
        if let hornType = commandDict["horn_type"] as? String {
            let duration = commandDict["duration"] as? TimeInterval ?? 0.1
            let description = commandDict["description"] as? String ?? "鸣笛"
            
            print("[AIService] 鸣笛指令格式: hornType=\(hornType), duration=\(duration)")
            
            // 根据鸣笛类型和持续时间获取参数
            let hornParameters = parseHornType(hornType, duration: duration)
            
            return CarControlCommand(
                direction: .horn,
                speed: .stop,
                duration: duration,
                hornParameters: hornParameters
            )
        }
        
        // 新的连续速度控制格式
        if let speedX = commandDict["speed_x"] as? Int,
           let speedY = commandDict["speed_y"] as? Int {
            
            // 解析持续时间
            let duration = commandDict["duration"] as? TimeInterval ?? 1.0
            
            // 解析描述，用于区分旋转和平移
            let description = commandDict["description"] as? String ?? ""
            
            print("[AIService] 速度控制格式: speedX=\(speedX), speedY=\(speedY), duration=\(duration), description=\(description)")
            
            // 根据速度分量和描述确定方向和速度级别
            let (direction, speedLevel) = parseSpeedComponents(speedX: speedX, speedY: speedY, description: description)
            
            print("[AIService] 解析结果: direction=\(direction.rawValue), speed=\(speedLevel.description)")
            
            return CarControlCommand(
                direction: direction,
                speed: speedLevel,
                duration: duration
            )
        }
        
        // 兼容旧的格式
        if let directionString = commandDict["direction"] as? String,
           let speedString = commandDict["speed"] as? String {
            
            print("[AIService] 旧格式: direction=\(directionString), speed=\(speedString)")
            
            // 解析方向
            let direction = parseDirection(directionString)
            
            // 解析速度
            let speed = parseSpeed(speedString)
            
            // 解析持续时间
            let duration = commandDict["duration"] as? TimeInterval
            
            return CarControlCommand(
                direction: direction,
                speed: speed,
                duration: duration
            )
        }
        
        print("[AIService] 无法解析命令，缺少必要字段")
        return nil
    }
    
    private func parseSpeedComponents(speedX: Int, speedY: Int, description: String) -> (Direction, SpeedLevel) {
        // 根据速度分量确定运动方向和速度级别
        let absSpeedX = abs(speedX)
        let absSpeedY = abs(speedY)
        let maxSpeed = max(absSpeedX, absSpeedY)
        
        // 确定速度级别
        let speedLevel: SpeedLevel
        if maxSpeed <= 40 {
            speedLevel = .slow
        } else if maxSpeed <= 70 {
            speedLevel = .medium
        } else {
            speedLevel = .fast
        }
        
        // 确定运动方向
        let direction: Direction
        if absSpeedY > absSpeedX {
            // 主要是前进/后退运动
            if speedY > 0 {
                direction = .forward
            } else if speedY < 0 {
                direction = .backward
            } else {
                direction = .stop
            }
        } else if absSpeedX > 0 {
            // 主要是转向运动，根据描述区分旋转和平移
            if speedX > 0 {
                // 向右运动
                if description.contains("平移") {
                    direction = .rightShift  // 右平移
                } else {
                    direction = .right       // 右旋转（默认）
                }
            } else {
                // 向左运动
                if description.contains("平移") {
                    direction = .leftShift   // 左平移
                } else {
                    direction = .left        // 左旋转（默认）
                }
            }
        } else {
            // 两个分量都是0
            direction = .stop
        }
        
        return (direction, speedLevel)
    }
    
    private func parseHornType(_ hornType: String, duration: TimeInterval) -> HornParameters {
        // 优先使用传入的duration，如果hornType是数字，直接使用
        if let customDuration = Double(hornType) {
            // 如果hornType是数字，表示直接指定持续时间（秒）
            return HornParameters.forBeat(duration: customDuration)
        }
        
        switch hornType.lowercased() {
        case "short", "短", "短促":
            return HornParameters.forBeat(duration: min(duration, 0.1))  // 短促鸣笛，最长0.1秒
        case "medium", "中等", "中":
            return HornParameters.forBeat(duration: duration > 0.3 ? duration : 0.15)  // 中等鸣笛
        case "long", "长", "长鸣":
            return HornParameters.forBeat(duration: max(duration, 0.3))   // 长鸣笛，最短0.3秒
        case "beat", "节拍", "节奏":
            return HornParameters.forBeat(duration: duration)             // 节拍鸣笛，使用指定时长
        case "rhythm", "旋律":
            return HornParameters.forBeat(duration: duration)             // 旋律鸣笛，使用指定时长
        case "tick", "滴答", "嘀":
            return HornParameters.forBeat(duration: min(duration, 0.06))  // 滴答声，极短
        case "quarter", "四分音符", "四分":
            return HornParameters.forBeat(duration: max(duration, 0.25))  // 四分音符
        case "half", "二分音符", "二分":
            return HornParameters.forBeat(duration: max(duration, 0.5))   // 二分音符
        case "whole", "全音符", "全音":
            return HornParameters.forBeat(duration: max(duration, 1.0))   // 全音符
        case "sustained", "持续", "延长":
            return HornParameters.forBeat(duration: max(duration, 1.5))   // 持续音
        default:
            // 默认使用传入的duration创建自定义鸣笛
            return HornParameters.forBeat(duration: duration)
        }
    }
    
    private func parseDirection(_ directionString: String) -> Direction {
        switch directionString.lowercased() {
        case "前进", "forward":
            return .forward
        case "后退", "backward":
            return .backward
        case "左转", "left", "左旋转", "left_rotate", "左旋":
            return .left        // 左旋转
        case "右转", "right", "右旋转", "right_rotate", "右旋":
            return .right       // 右旋转
        case "左平移", "left_shift":
            return .leftShift   // 左平移
        case "右平移", "right_shift":
            return .rightShift  // 右平移
        case "鸣笛", "horn":
            return .horn        // 鸣笛
        default:
            return .stop
        }
    }
    
    private func parseSpeed(_ speedString: String) -> SpeedLevel {
        switch speedString.lowercased() {
        case "低速", "slow":
            return .slow
        case "中速", "medium":
            return .medium
        case "高速", "fast":
            return .fast
        default:
            return .medium
        }
    }
}

// MARK: - 扩展：度数映射和预定义命令
extension AIService {
    
    // 度数到时间的映射函数
    static func degreesToDuration(_ degrees: Double, speed: SpeedLevel) -> TimeInterval {
        // 基础转速：medium速度下135度/秒
        let baseDegreesPerSecond: Double = 135.0
        
        // 不同速度的倍数
        let speedMultiplier: Double
        switch speed {
        case .stop:
            return 0.0
        case .slow:
            speedMultiplier = 0.6  // 81度/秒
        case .medium:
            speedMultiplier = 1.0  // 135度/秒
        case .fast:
            speedMultiplier = 1.6  // 216度/秒
        case .turbo:
            speedMultiplier = 2.0  // 270度/秒
        }
        
        let actualDegreesPerSecond = baseDegreesPerSecond * speedMultiplier
        let duration = degrees / actualDegreesPerSecond
        
        // 确保最小时间为0.1秒，最大时间为10秒
        return max(0.1, min(10.0, duration))
    }
    
    // 预定义的常用命令 - 使用准确的度数映射和舞蹈动作
    static let predefinedCommands: [String: [CarControlCommand]] = [
        "走正方形": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),  // 90度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),  // 90度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),  // 90度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium))   // 90度右转
        ],
        "走圆形": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),       // 45度右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow))        // 45度右转，共360度
        ],
        "前进10米": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 5.0)
        ],
        "后退5米": [
            CarControlCommand(direction: .backward, speed: .medium, duration: 2.5)
        ],
        "左转90度": [
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(90, speed: .medium))     // 准确的90度左转
        ],
        "右转90度": [
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium))    // 准确的90度右转
        ],
        "停止": [
            CarControlCommand(direction: .stop, speed: .stop)
        ],
        "绕障碍物": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0), // 前进
            CarControlCommand(direction: .right, speed: .medium, duration: 1.0),   // 右转
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0), // 前进
            CarControlCommand(direction: .left, speed: .medium, duration: 1.0),    // 左转
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0)  // 前进
        ],
        
        // 舞蹈动作
        "跳一段简单的舞": [
            // 第一段：前进后退节拍
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            
            // 第二段：左右旋转
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(45, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(90, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(45, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            
            // 第三段：混合动作
            CarControlCommand(direction: .leftShift, speed: .medium, duration: 0.2),
            CarControlCommand(direction: .rightShift, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .leftShift, speed: .medium, duration: 0.2),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3)
        ],
        
        "快速摆动舞": [
            // 连续快速左右摆动
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.15),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            
            // 变速摆动
            CarControlCommand(direction: .leftShift, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .rightShift, speed: .medium, duration: 0.2),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.1),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.1),
            CarControlCommand(direction: .leftShift, speed: .medium, duration: 0.2),
            CarControlCommand(direction: .rightShift, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.5)
        ],
        
        "旋转舞": [
            // 高速旋转序列
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(180, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(180, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(360, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            
            // 慢速精准旋转
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.5)
        ],
        
        "8字舞": [
            // 画8字：第一个圆
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            
            // 第二个圆（反方向）
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium))
        ],
        
        "摇摆舞": [
            // 左右摇摆加前进后退
            CarControlCommand(direction: .leftShift, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.2),
            CarControlCommand(direction: .rightShift, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.2),
            CarControlCommand(direction: .leftShift, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .backward, speed: .slow, duration: 0.2),
            CarControlCommand(direction: .rightShift, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .backward, speed: .slow, duration: 0.2),
            
            // 重复模式，更快
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.2),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.1),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.2),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.1),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.2),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.1),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.2),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.1),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.5)
        ],
        
        "节拍舞": [
            // 4/4拍节奏
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.25),   // 第1拍
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.25),        // 停顿
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.25),  // 第2拍
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.25),        // 停顿
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(90, speed: .fast)), // 第3拍
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.25),        // 停顿
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(90, speed: .fast)), // 第4拍
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.5),         // 长停顿
            
            // 重复变奏
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.125),   // 快拍
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.125),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.125),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.125),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.5),     // 长拍
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.5),
            CarControlCommand(direction: .stop, speed: .stop, duration: 1.0)
        ],
        
        // 复杂动作
        "走S形路线": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(30, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(30, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(60, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(30, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(30, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0)
        ],
        
        "画一个心形": [
            // 心形左半部分
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.5),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(45, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.5),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(45, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            
            // 心形右半部分
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.5),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(90, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.5),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(45, speed: .slow))
        ],
        
        "螺旋前进": [
            // 小圆圈螺旋
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.4),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.5),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.6),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.7),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.8),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.9),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(90, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.0)
        ],
        
        "Z字形移动": [
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.5),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.5),
            CarControlCommand(direction: .right, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 2.0),
            CarControlCommand(direction: .left, speed: .medium, duration: degreesToDuration(45, speed: .medium)),
            CarControlCommand(direction: .forward, speed: .medium, duration: 1.5)
        ],
        
        "花样表演": [
            // 复合花样动作
            CarControlCommand(direction: .forward, speed: .fast, duration: 0.5),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(360, speed: .fast)), // 快速转圈
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.5),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.3),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.6),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.3),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.8),
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(180, speed: .fast)),
            CarControlCommand(direction: .backward, speed: .fast, duration: 0.8),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(180, speed: .fast)),
            CarControlCommand(direction: .stop, speed: .stop, duration: 1.0)
        ],
        
        "模拟醉酒行走": [
            // 随机摇摆行走
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.5),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(15, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(30, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.4),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(20, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.6),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(25, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.3),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(10, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.5),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(35, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.4),
            CarControlCommand(direction: .left, speed: .slow, duration: degreesToDuration(15, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.7),
            CarControlCommand(direction: .right, speed: .slow, duration: degreesToDuration(20, speed: .slow)),
            CarControlCommand(direction: .forward, speed: .slow, duration: 0.2)
        ],
        
        // 带鸣笛的音乐舞蹈（新增）
        "音乐舞蹈": [
            // 开场鸣笛
            CarControlCommand.horn(parameters: .long, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            
            // 第一段：前进配节拍
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.4),
            CarControlCommand.horn(parameters: .beat, duration: 0.1),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.3),
            CarControlCommand.horn(parameters: .beat, duration: 0.1),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.4),
            CarControlCommand.horn(parameters: .beat, duration: 0.1),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            
            // 第二段：旋转配音乐
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(90, speed: .fast)),
            CarControlCommand.horn(parameters: .rhythm, duration: 0.2),
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(180, speed: .fast)),
            CarControlCommand.horn(parameters: .rhythm, duration: 0.2),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(90, speed: .fast)),
            CarControlCommand.horn(parameters: .beat, duration: 0.1),
            
            // 第三段：摆动配快拍
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.2),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.2),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .leftShift, speed: .fast, duration: 0.2),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .rightShift, speed: .fast, duration: 0.2),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            
            // 结尾
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            CarControlCommand.horn(parameters: .long, duration: 0.5)
        ],
        
        "播放音乐": [
            // 纯音乐序列
            CarControlCommand.horn(parameters: .beat, duration: 0.2),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .beat, duration: 0.2),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .rhythm, duration: 0.3),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .medium, duration: 0.25),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.15),
            CarControlCommand.horn(parameters: .long, duration: 0.4),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.3),
            CarControlCommand.horn(parameters: .beat, duration: 0.2),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .beat, duration: 0.2),
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.1),
            CarControlCommand.horn(parameters: .rhythm, duration: 0.3)
        ],
        
        "节拍跳舞": [
            // 强调节拍的舞蹈
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.25),
            CarControlCommand.horn(parameters: .beat, duration: 0.15),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.25),
            CarControlCommand.horn(parameters: .beat, duration: 0.15),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.25),
            CarControlCommand.horn(parameters: .beat, duration: 0.15),
            CarControlCommand(direction: .forward, speed: .medium, duration: 0.25),
            CarControlCommand.horn(parameters: .rhythm, duration: 0.2),
            
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(45, speed: .fast)),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .right, speed: .fast, duration: degreesToDuration(90, speed: .fast)),
            CarControlCommand.horn(parameters: .short, duration: 0.1),
            CarControlCommand(direction: .left, speed: .fast, duration: degreesToDuration(45, speed: .fast)),
            CarControlCommand.horn(parameters: .beat, duration: 0.15),
            
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.3),
            CarControlCommand.horn(parameters: .medium, duration: 0.2),
            CarControlCommand(direction: .backward, speed: .medium, duration: 0.3),
            CarControlCommand.horn(parameters: .medium, duration: 0.2),
            
            CarControlCommand(direction: .stop, speed: .stop, duration: 0.2),
            CarControlCommand.horn(parameters: .long, duration: 0.4)
        ]
    ]
    
    // 检查是否为预定义命令
    func isPredefinedCommand(_ command: String) -> Bool {
        return AIService.predefinedCommands.keys.contains { key in
            command.lowercased().contains(key.lowercased())
        }
    }
    
    // 获取预定义命令
    func getPredefinedCommands(_ command: String) -> [CarControlCommand]? {
        for (key, commands) in AIService.predefinedCommands {
            if command.lowercased().contains(key.lowercased()) {
                return commands
            }
        }
        return nil
    }
} 